package com.lingshi.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.shopping.entity.Permission;
import com.lingshi.shopping.entity.RolePermission;
import com.lingshi.shopping.enums.ErrorEnums;
import com.lingshi.shopping.exception.BusException;
import com.lingshi.shopping.service.PermissionService;
import com.lingshi.shopping_admin_service.mapper.PermissionMapper;
import com.lingshi.shopping_admin_service.mapper.RolePermissionMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Override
    public void add(Permission permission) {
        permissionMapper.insert(permission);
    }

    @Override
    public void update(Permission permission) {
        permissionMapper.updateById(permission);
    }

    @Override
    public void delete(Long pid) {
        /**
         * 1, 判断中间表是否有角色关联权限，如果有，不能删除
         * 2，没有：删除
         */
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getPid,pid);
        //角色是否拥有权限
        Long count = rolePermissionMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusException(ErrorEnums.ROLE_HAS_PERMISSION_ERROR);
        }

        permissionMapper.deleteById(pid);

    }

    @Override
    public Permission findById(Long pid) {
        return permissionMapper.selectById(pid);
    }

    @Override
    public Page<Permission> search(int page, int size) {
        Page<Permission> pages = new Page<>(page, size);
        permissionMapper.selectPage(pages, null);
        return pages;
    }

    @Override
    public List<Permission> findAll() {
        return permissionMapper.selectList(null);
    }
}
